package com.hsc.msmservice.contorller;


import com.hsc.commonutils.R;
import com.hsc.msmservice.service.MsmService;
import com.hsc.msmservice.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
//@CrossOrigin //gateway解决了可以注掉
public class MsmController {

    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    //发送短信的方法
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone) {
        //1从redis获取验证码，如果取到则直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }
        //redis获取不到验证码，进行阿里云发送

        //生成随机值，传送阿里云发送
        code = RandomUtil.getFourBitRandom();
        Map<String,Object> para = new HashMap<>();
        para.put("code",code);
        //调用service发送短信方法
        boolean isSend = msmService.send(para,phone);
        if(isSend){
            //发送成功，把短信验证码放到redis里面
            //设置有效时间
            redisTemplate.opsForValue().set(phone,code,5,TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error().message("短信验证码发送失败");
        }
    }
}
